﻿using LanguagePolish.EntityModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LanguagePolish.Models
{
    class ClassesModel
    {
        public bool CanUserAddClasses
        {
            get
            {
                return LinksProvider.Model.CurrentUser.AccountType.AddPermission == true;
            }
        }

        public bool CanUserRemoveClasses
        {
            get { return LinksProvider.Model.CurrentUser.AccountType.DeletePermission == true; }
        }

        public bool CanUserEditClasses
        {
            get { return LinksProvider.Model.CurrentUser.AccountType.EditClassesPermission == true; }
        }

        public IEnumerable<Class> GetClassesWithFilter(string filter = null)
        {
            var teacher = LinksProvider.Model.CurrentUser.Teacher;
            if (LinksProvider.Model.IsSeeAll || teacher == null)
            {
                var context = LinksProvider.Model.EntityContext;
                if (string.IsNullOrWhiteSpace(filter))
                    return context.Classes;
                var res =
                    context.Classes.ToList()
                        .Where(t => t.ClassName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1);
                // TODO: по идее так оптимальнее, но почему-то не работает
                //var res = context.Teachers.Where(s => SqlFunctions.CharIndex(s.Name, filter) != 0);
                return res;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(filter))
                    return teacher.Classes;
                var res = teacher.Classes.ToList()
                        .Where(t => t.ClassName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1);
                return res;
            }
        }

        public void AddClass(Class myClass)
        {
            var context = LinksProvider.Model.EntityContext;
            context.Classes.Add(myClass);
            context.SaveChanges();
        }

        public void RollbackClass(Class myClass)
        {
            var context = LinksProvider.Model.EntityContext;
            context.Rollback(myClass);
        }

        public void SaveChanges()
        {
            LinksProvider.Model.EntityContext.SaveChanges();
        }

        public void DeleteClass(Class myClass)
        {
            var context = LinksProvider.Model.EntityContext;
            context.Classes.Remove(myClass);
            context.SaveChanges();
        }
    }
}
